<template>
  <div class="activity-detail page-container">
    <!-- 导航栏 -->
    <van-nav-bar :title="activity?.title || '活动详情'" left-arrow @click-left="router.back()">
      <template #right>
        <van-icon name="like-o" class="nav-icon" :class="{ 'is-favorite': isFavorite }" @click="toggleFavorite" />
        <van-icon name="share-o" class="nav-icon" @click="handleShare" />
      </template>
    </van-nav-bar>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <!-- 主要内容区域 -->
    <div class="content content-container" v-if="activity">
      <!-- 基本信息卡片 -->
      <activity-basic-info :activity="activity" />

      <!-- 活动详情卡片 -->
      <activity-detail-info :activity="activity" />

      <!-- 路线信息卡片 -->
      <activity-route-info :location="activity.location" :address="activity.address" :routeDescription="activity.routeDescription" />

      <!-- 装备和注意事项 -->
      <activity-requirements :equipmentRequired="activity.equipmentRequired" :requirements="activity.requirements" />

      <!-- 参与者列表 -->
      <activity-participants :participants="activity.participants" :maxParticipants="activity.maxParticipants" />

      <!-- 评论区 -->
      <activity-comments :activityId="activity.id" @comment-added="handleCommentAdded" />
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="price">
        <span class="label">费用：</span>
        <span class="amount">¥{{ activity?.price || 0 }}</span>
      </div>
      <van-button type="primary" block @click="handleJoin">立即报名</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { useActivityStore } from '@/stores/activity'
import type { Activity } from '@/types/activity'
import ActivityBasicInfo from '@/views/Activity/components/ActivityBasicInfo.vue'
import ActivityDetailInfo from '@/views/Activity/components/ActivityDetailInfo.vue'
import ActivityRouteInfo from '@/views/Activity/components/ActivityRouteInfo.vue'
import ActivityRequirements from '@/views/Activity/components/ActivityRequirements.vue'
import ActivityParticipants from '@/views/Activity/components/ActivityParticipants.vue'
import ActivityComments from '@/views/Activity/components/ActivityComments.vue'

const route = useRoute()
const router = useRouter()
const activityStore = useActivityStore()

const activity = ref<Activity | null>(null)
const loading = ref(true)
const isFavorite = ref(false)
const showShare = ref(false)
const isJoined = ref(false)

// 分享选项
const shareOptions = [
  { name: '微信', icon: 'wechat' },
  { name: '朋友圈', icon: 'wechat-moments' },
  { name: '复制链接', icon: 'link' }
]

// 计算属性
const isActivityFull = computed(() => {
  if (!activity.value) return true
  return activity.value.currentParticipants >= activity.value.maxParticipants
})

const isExpired = computed(() => {
  if (!activity.value?.startTime) return true
  return new Date(activity.value.startTime) < new Date()
})

const joinButtonText = computed(() => {
  if (isJoined.value) return '已报名'
  if (isActivityFull.value) return '活动已满'
  if (isExpired.value) return '活动已结束'
  return '立即报名'
})

// 方法
const fetchActivityDetail = async () => {
  try {
    const id = route.params.id as string
    loading.value = true

    const [activityData, favoriteStatus, joinStatus] = await Promise.all([
      activityStore.fetchActivityDetail(id),
      activityStore.checkFavorite(id),
      activityStore.checkJoinStatus(id)
    ])

    console.log('原始活动数据:', activityData) // 添加日志查看原始数据

    // 检查数据是否在 response.data 中
    const data = activityData.data || activityData

    // 确保数据格式正确
    activity.value = {
      id: data.id,
      title: data.title,
      description: data.description,
      cover: data.cover,
      startTime: data.startTime || data.start_time,
      endTime: data.endTime || data.end_time,
      location: data.location,
      address: data.address,
      currentParticipants:
        data.currentParticipants || data.current_participants || 0,
      maxParticipants: data.maxParticipants || data.max_participants || 10,
      feeMode: data.feeMode || data.fee_mode || 'FREE',
      feeAmount: data.feeAmount || data.fee_amount || 0,
      tag: data.tag || [],
      participants: data.participants || [],
      equipmentRequired:
        data.equipmentRequired || data.equipment_required || '',
      requirements: data.requirements || '',
      routeDescription: data.routeDescription || data.route_description || '',
      ...data // 保留其他可能的字段
    }

    console.log('处理后的活动数据:', activity.value) // 添加日志

    isFavorite.value = favoriteStatus
    isJoined.value = joinStatus
  } catch (error) {
    console.error('获取活动详情失败:', error)
    showToast('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

const handleJoin = async () => {
  if (!activity.value) return

  try {
    await showDialog({
      title: '确认报名',
      message: '是否确认报名参加该活动？',
      confirmButtonText: '确认报名',
      cancelButtonText: '取消'
    })

    await activityStore.joinActivity(activity.value.id)
    showToast('报名成功')
    isJoined.value = true
    await fetchActivityDetail() // 刷新活动信息
  } catch (error) {
    if (error === 'cancel') return
    console.error('报名失败:', error)
    showToast('报名失败')
  }
}

const toggleFavorite = async () => {
  if (!activity.value) return

  try {
    if (isFavorite.value) {
      await activityStore.unfavoriteActivity(activity.value.id)
      showToast('已取消收藏')
    } else {
      await activityStore.favoriteActivity(activity.value.id)
      showToast('收藏成功')
    }
    isFavorite.value = !isFavorite.value
  } catch (error) {
    console.error('操作失败:', error)
    showToast('操作失败')
  }
}

const handleShare = () => {
  showShare.value = true
}

const onShareSelect = (option: { name: string }) => {
  console.log('分享到:', option.name)
  showToast(`分享到${option.name}功能开发中`)
  showShare.value = false
}

const handleCommentAdded = () => {
  fetchActivityDetail() // 刷新评论数据
}

onMounted(() => {
  fetchActivityDetail()
})
</script>

<style scoped lang="scss">
.activity-detail {
  .nav-icon {
    margin-left: 16px;
    font-size: 20px;

    &.is-favorite {
      color: #ff9800;
    }
  }

  .loading-container {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .bottom-bar {
    padding: 8px 16px calc(8px + env(safe-area-inset-bottom));
    background: #fff;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    gap: 16px;
    z-index: 100;

    @media screen and (min-width: 600px) {
      max-width: 600px;
      left: 50%;
      transform: translateX(-50%);
    }

    .price {
      flex-shrink: 0;

      .label {
        color: #666;
      }

      .amount {
        color: #ff5722;
        font-size: 20px;
        font-weight: bold;
      }
    }

    .van-button {
      flex: 1;
      height: 40px;
      border-radius: 20px;
    }
  }
}
</style>





